import { Modal, message, notification } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { useMapMainContext } from '@contexts/mapMainContext'
import { getQueryString } from '@commonMethod'
import { session } from '@core'
import copy from "copy-to-clipboard";
import custom_map_config from "@utils/custom_map_config";
import { receiveMapPlace, encryptMapPlace } from "@apis/riskPositionApi";

import position from "./images/position.png";
import styles from "./styles/riskPosition.module.css";

const { confirm } = Modal;

export const useUtils = (setSpinning, setIsNoAccess) => {
  let map = null;
  let AC = null;
  let readonly = false
  let returnUrl = ''
  let businessNo = ''

  const { isMap } = useMapMainContext()

  let Geoc = null
  let Geol = null

  const initMap = () => {
    map = new BMapGL.Map("container", { enableMapClick: false }); // 创建Map实例
    map.centerAndZoom(new BMapGL.Point(108.19706194604755, 34.33234901650633), 6); // 初始化地图,设置中心点坐标和地图级别
    map.setMinZoom(5);
    map.setMapType(BMAP_SATELLITE_MAP);
    map.setMapStyleV2({
      styleJson: custom_map_config
    });
    map.enableScrollWheelZoom(true); //启用地图滚轮放大缩小
    map.disableDoubleClickZoom(); //	取消地图双击缩放
    Geoc = new BMapGL.Geocoder(); // 用于获取用户的地址解析
    Geol = new BMapGL.Geolocation(); // 创建Geolocation对象实例

    map.addEventListener("tilesloaded", function (e) {
      console.log(e);
    })

    // 监听地图点击事件
    map.addEventListener("click", function (e) {
      setSpinning(true)
      map.clearOverlays(); //清除地图上所有覆盖物

      const pt = e.latlng; //以当前点为坐标进行搜索
      Geoc.getLocation(pt, function (location) {
        map.centerAndZoom(pt, 19);
        initRegions(location);
      });
    });

  };

	function setPlace(myValue){
		map.clearOverlays();    //清除地图上所有覆盖物
		const local = new BMapGL.LocalSearch(map, {
      onSearchComplete: function (res) {
        console.log(local.getResults().getPoi(0))
        console.log('')
        map.clearOverlays(); // 清除地图上所有覆盖物
        const pp = local.getResults().getPoi(0)?.point; //获取第一个智能搜索结果的坐标
        if (pp) {
          map.centerAndZoom(pp, 19);
          initRegions(res.getPoi(0));
          setSpinning(false)
          return
        }
        setPlace(myValue);
      },
    });
		local.search(myValue);
	}

  // 创建自动提示类的实例配置
  const Autocomplete = () => {
    console.count('Autocomplete');
    //建立一个自动完成的对象
    AC = new BMapGL.Autocomplete({
      input: "searchInput",
      location: map,
    });

    // 监听回车选中某条记录
    AC.addEventListener("onconfirm", function (e) {
      const _value = e.item.value;
      const addr =
        _value.province +
        _value.city +
        _value.district +
        _value.street +
        _value.streetNumber +
        _value.business;
      setPlace(addr)
      setSpinning(true)
    });
  }

  function initRegions(current) {
    AC.setLocation(current.point) // 设置检索范围
    const { address } = current
    const { lng, lat } = current.point
    const pt = current.point; // 以指定的经度和纬度创建一个地理点坐标

    const myIcon = new BMapGL.Icon(position, new BMapGL.Size(32, 32));
    const offset = new BMapGL.Size(0, -16);
    const marker = new BMapGL.Marker(pt, { icon: myIcon, offset }); //添加标记

    map.addOverlay(marker);

    const content = `<div class="${styles.assress_box}">
      <div class="${styles.child_one}">
        <div class="${styles.coordinates}">
          <div class="${styles.title}">经度：</div>
          <div class="${styles.text}">${lng}</div>
        </div>
  
        <div class="${styles.coordinates}">
          <div class="${styles.title}">纬度：</div>
          <div class="${styles.text}">${lat}</div>
        </div>
      </div>
  
      <div class="${styles.child_two}">
        <div class="${styles.assress}">
          <div class="${styles.title}">地址：</div>
          <textarea disabled="disabled" id="${styles.assressText}" class="${styles.text}">${address}</textarea>
        </div>
      </div>
  
      ${ readonly ? '' : `<button id="btnclick" type="button" class="${styles.btn}">${isMap ? '提交' : '复制'}</button>`}
    </div>`;

    const infoWindow = new BMapGL.InfoWindow(content, { offset }); // 创建信息窗口对象
    infoWindow.setWidth(520);

    map.openInfoWindow(infoWindow, pt);

    setTimeout(function () {
      if (readonly) return
      const btnclick = document.getElementById("btnclick");
      btnclick.onclick = () => {
        if(isMap) {
          showPromiseConfirm(current)
          return
        }
        copy( `经度：${lng} , 纬度：${lat} , 地址：${address}` );
        message.success("复制成功");
        
      };
      setSpinning(false);
    }, 200);
  }

  function showPromiseConfirm(ConfirData) {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定要提交吗？',
      onOk() {
        return new Promise (async (resolve, reject) => {
          const parmas = {
            returnUrl,
            businessNo,
            address: ConfirData.address,
            longitude: ConfirData.point.lng,
            latitude: ConfirData.point.lat,
            partnerCode: getQueryString('partnerCode'),
            encryptData: getQueryString('encryptData'),
          };
          const {data, error} = await encryptMapPlace(parmas)
          if (error) return
          resolve()
          window.open(`${returnUrl}?encryptData=${data.encryptData}&partnerCode=${data.partnerCode}`)
        })
      },
      onCancel() {},
    });
  };

  // 根据解密后返回的地址信息，解析出百度地图地址信息
  const getPoint = (address) => {
    Geoc.getPoint(address, (point) => {
      // console.log('getPoint解析后的坐标地址===>',point);
      if (point) {
        getLocation(point);
      } else {
        message.error("当前地址没有解析到结果!");
      }
    });
  };

  // 根据解密后返回的经纬度，解析出百度地图地址信息
  const getLocation = (point) => {
    Geoc.getLocation(point, (location) => {
      // console.log('getLocation解析后的坐标地址===>',location.point);
      if (location.point) {
        initRegions(location);
        map.centerAndZoom(location.point, 19);
      } else {
        message.error("当前地址没有解析到结果!");
      }
    });
  };

  const init = async () => {

    try { // 检测 BMapGL 是否存在
      new BMapGL.Geocoder()
    } catch (error) {
      console.error(error);
      notification.error({
        message: '温馨提醒',
        description: '地图加载失败，请检查网络或尝试刷新页面',
        placement: 'top',
      })
      return
    }

    initMap();
    Autocomplete();

    if(!isMap) return
    setSpinning(true)
    const { data, error } = await receiveMapPlace();
    setSpinning(false)
    if (error) return setIsNoAccess(true)

    session.set('token', data.token)
    readonly = Number(data.readonly) ? true : false
    returnUrl = data.returnUrl
    businessNo = data.businessNo
    AC.setInputValue(data.address);

    //传了经纬度
    if (data.longitude && data.latitude) {
      getLocation(new BMapGL.Point(data.longitude, data.latitude));
    }

    const address = data.provinceName + data.cityName + data.countyName + data.address;
    // 只传了地址
    if (address && !(data.latitude && data.longitude)) {
      getPoint(address);
    }

    // 详细地址没传，并且省市区没传，并且坐标也没传的情况下，用浏览器定位
    if (!address && !(data.latitude && data.longitude)) {
      Geol.getCurrentPosition(
        function (r) {
          if (this.getStatus() === BMAP_STATUS_SUCCESS) {
            const mk = new BMapGL.Marker(r.point);
            map.addOverlay(mk);
            map.centerAndZoom(location.point, 19);
            showLoading(false)
          }
        },
        { enableHighAccuracy: true }
      );
    }
  };

  return {
    init
  };
};
